﻿using System;
using System.Linq;
using System.Web.Mvc;
using Gxu.Models;

namespace Easy.Admin
{
    public class MenuConfig
    {
        public static void RegisterMenu()
        {
            //获取所有程序集中类型名包含 Controller 的类型
            var allTypes = AppDomain.CurrentDomain.GetAssemblies().SelectMany(sm => sm.GetTypes().Where(w => w.Name.EndsWith("Controller"))).ToArray();

            foreach (var controller in allTypes)
            {
                //过滤抽象类
                if (controller.IsAbstract) continue;

                //是否是控制器
                if (!IsController(controller)) continue;

                var controllerName = controller.Name.Replace("Controller", "");
                var controllerDisplayName = controller.GetDisplayName();

                var parentMenu = Menus.Find(Menus._.Controller == controllerName & Menus._.Action == "");

                if (parentMenu == null)
                {
                    parentMenu = new Menus
                    {
                        Name = controllerDisplayName,
                        Controller = controllerName,
                        Action = ""
                    };
                    parentMenu.Insert();
                }

                var parentAction = Actions.Find(Actions._.Name == controllerDisplayName & Actions._.IsGroup == true);

                if (parentAction == null)
                {
                    parentAction = new Actions
                    {
                        Name = controller.GetDisplayName(),
                        IsGroup = true,
                    };
                    parentAction.Insert();
                }

                var methods = controller.GetMethods().Where(w =>
                    w.IsPublic &&
                    !w.IsStatic &&
                    (w.ReturnType == typeof(ActionResult) ||
                     w.ReturnType.BaseType == typeof(ActionResult)||
                     w.ReturnType.BaseType?.BaseType == typeof(ActionResult)));

                foreach (var methodInfo in methods)
                {
                    var actionName = methodInfo.Name;
                    var name = actionName == "Index" ? $"{controllerDisplayName}列表" :
                                actionName == "Add" ? $"新增{controllerDisplayName}" :
                                actionName == "Edit" ? $"编辑{controllerDisplayName}" :
                                actionName;

                    var childAction = Actions.Find(Actions._.Name == name & Actions._.IsGroup == false);

                    if (childAction == null)
                    {
                        childAction = new Actions
                        {
                            Name = name,
                            ParentID = parentAction.ID,
                        };
                        childAction.Insert();
                    }

                    //如果是视图，添加菜单
                    if (methodInfo.ReturnType == typeof(ViewResult))
                    {
                        var childMenu = Menus.Find(Menus._.Controller == controllerName & Menus._.Action == actionName);

                        if (childMenu == null)
                        {
                            childMenu = new Menus
                            {
                                Name = name,
                                ParentID = parentMenu.ID,
                                Controller = controllerName,
                                Action = actionName,
                                URL = $"/{controllerName}/{actionName}/",
                            };
                            childMenu.Insert();
                        }

                        var menuActionMap = MenuActionMap.FindByMenuIDAndActionID(childMenu.ID, childAction.ID);

                        if (menuActionMap == null)
                        {
                            menuActionMap = new MenuActionMap
                            {
                                MenuID = childMenu.ID,
                                ActionID = childAction.ID,
                            };
                            menuActionMap.Insert();
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 判断是否是控制器
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        private static bool IsController(Type t)
        {
            while (true)
            {
                if (t.BaseType == null || t.BaseType == typeof(object))
                {
                    return false;
                }
                else if (t.BaseType == typeof(Controller))
                {
                    return true;
                }
                else
                {
                    t = t.BaseType;
                }
            }
        }
    }
}
